package com.jc.order.controller;

import cn.hutool.core.util.StrUtil;
import com.jc.constant.PolicyAttachmentTypeConst;
import com.jc.order.constant.OrderConst;
import com.jc.order.dto.JcPolicyDTO;
import com.jc.order.dto.SystemTenantDTO;
import com.jc.order.service.*;
import com.jc.util.Result;
import com.jc.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("cross/v1")
@Slf4j
public class CrossOrderController extends BaseOrderController {
    @Resource(name = "insuranceCrossValidateService")
    private CargoValidateService cargoValidateService;

    @Autowired
    private InsuranceCrossService insuranceCrossService;
    @Autowired
    private ApiBaseService apiBaseService;

    @Override
    protected CargoCrossBorderService<JcPolicyDTO> getInsuranceService() {
        return insuranceCrossService;
    }

    @Override
    protected CargoValidateService getValidateService() {
        return cargoValidateService;
    }

    @Override
    protected String getProductCode() {
        return OrderConst.PRODUCT_CODE_2;
    }


    @Override
    protected void buildInsuranceData(PolicyRequest request, SystemTenantDTO tenant, JcPolicyDTO dto) {
        JcPolicyDTO policyDTO = apiBaseService.buildBaseInsuranceData(request, tenant);
        BeanUtils.copyProperties(policyDTO, dto);
        setBusinessFields(request, dto);
        processAttachments(request, dto);
    }

    // 特有方法：保费计算
    @RequestMapping("calculate")
    public Result<PolicyCalculateVo> calculate(@RequestBody OrderRequest request) {
        Result result = new Result<>();
        result.ok();
        try {
            SystemTenantDTO tenant = apiBaseService.validateBaseInfo(request, result);
            if (!result.getSuccess()) return result;

            PolicyRequest policyRequest = apiBaseService.parseRequestData(request.getData(), result);
            if (!result.getSuccess()) return result;

            JcPolicyDTO policyDTO = apiBaseService.buildBaseInsuranceData(policyRequest, tenant);
            JcPolicyDTO dto = new JcPolicyDTO();
            BeanUtils.copyProperties(policyDTO, dto);

            calculateInsuranceFee(dto, result);
            return result;
        } catch (Exception e) {
            log.error("系统异常: ", e);
            return result.error("系统处理异常，请稍后重试");
        }
    }


    // 映射到父类方法
    @RequestMapping("createOrder")
    public Result<PolicyResponseVO> createOrder(@RequestBody OrderRequest request) {
        return super.createOrder(request);
    }

    @RequestMapping("calculatePolicy")
    public Result calculatePolicy(@RequestBody OrderRequest request) {
        return super.calculatePolicy(request);
    }










    /**
     * JC API
     * @param request
     * @return
     */
    @RequestMapping("createPolicy")
    public Result createPolicy(@RequestBody OrderRequest request) {




        return super.createPolicy(request);
    }

    @RequestMapping("updatePolicy")
    public Result updatePolicy(@RequestBody OrderRequest request) {
        return super.updatePolicy(request);
    }

    @RequestMapping("queryPolicy")
    public Result<List<PolicyVO>> queryPolicy(@RequestBody OrderRequest request) {
        return super.queryPolicy(request);
    }

    // 特有字段设置方法
    private void setBusinessFields(PolicyRequest request, JcPolicyDTO dto) {
        if (request == null) {
            return;
        }
        dto.setExpressCompany(request.getExpressCompanyCode());
        dto.setExpressTrackingNumber(request.getExpressNo());
        dto.setWarehousingNumber(request.getShipmentId());
        dto.setNote(request.getRemark());
        dto.setDeliveryAmount(request.getFreight());
        dto.setDeliveryCurrency(request.getFreightCurrencyCode());
        dto.setLostCareOnly(Optional.ofNullable(request.getLossOnly()).orElse(false));
        dto.setWarProtection(Optional.ofNullable(request.getWarRisk()).orElse(false));
        dto.setReturnProtection(Optional.ofNullable(request.getReplyPostRisk()).orElse(false));
        dto.setIncorrectDispatchProtection(Optional.ofNullable(request.getWrongAddressRisk()).orElse(false));
    }

    // 处理附件
    private void processAttachments(PolicyRequest request, JcPolicyDTO dto) {
        if (request == null) {
            return;
        }

        Optional.ofNullable(request.getAttachmentList()).orElse(Collections.emptyList()).stream()
                .filter(attachment -> attachment != null && StrUtil.isNotBlank(attachment.getType()))
                .forEach(attachment -> {
                    String type = attachment.getType().toLowerCase();
                    if (PolicyAttachmentTypeConst.INSURE_ATTACHED_FILE_EXPRESS_NO.equalsIgnoreCase(type)) {
                        dto.setExpressTrackingNumberFile(attachment.getUrl());
                    } else if (PolicyAttachmentTypeConst.INSURE_ATTACHED_FILE_CARGO_DESC.equalsIgnoreCase(type)) {
                        dto.setGoodsNoteFile(attachment.getUrl());
                    }
                });
    }






}